package com.smec.remes.module.search;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.acker.simplezxing.activity.CaptureActivity;
import com.google.gson.Gson;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.smec.moblie.R;
import com.smec.moblie.databinding.ActivitySearchBinding;
import com.smec.remes.base.SmecBaseActivity;
import com.smec.remes.bean.AbleMatnr;

import com.smec.remes.bean.query.MantrPrice;
import com.smec.remes.module.request.SmecRequestPresenter;
import com.smec.remes.module.search.adapter.SmecSearchAdapter;
import com.smec.remes.module.search.component.BottomDialog;
import com.smec.remes.module.search.component.CircleView;
import com.smec.remes.util.CommonUtils;
import com.smec.remes.util.GetFullUrl;
import com.smec.remes.util.TopBarLayout;
import com.smec.remes.util.WmsConstant;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by Administrator on 2017/11/28.
 */

public class SmecSearchActivity extends SmecBaseActivity<SmecRequestPresenter> {

    private ActivitySearchBinding activitySearchBinding;
    private String _PriceUrl="QueryProductPriceServicePS";
    public static final String SEARCH="SEARCH";
    public static final String ten="ten";
    public static final String tenFail="tenFail";
    public static final String Top="Top";
    public static final String SEARCHFAIL="SEARCHFAIL";
    public static final String RequestMantr="RequestMantr";

    private SmecSearchAdapter smecSearchAdapter;
    private Handler mHandler=new Handler();
    private int pageNumber=1;
    private String condition="";
    public static final String BUY_NULL="BUY_NULL";
    public static final String BUY_NOT_NULL="BUY_NOT_NULL";
    private LinearLayoutManager linearLayoutManager;
    private Boolean scanning=false;
    private String  status;
    private Boolean first=true;
    private Gson gson = new Gson();
    private ArrayList<AbleMatnr> newArraylist=new ArrayList<>();
    //绘图
    private ViewGroup viewGroup;

    //弹窗
    BottomDialog bottomDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activitySearchBinding=DataBindingUtil.setContentView(this, R.layout.activity_search);
        smecSearchAdapter=new SmecSearchAdapter(this,mRxBus);
        linearLayoutManager=new LinearLayoutManager(SmecSearchActivity.this);
        activitySearchBinding.searchRecyclerView.setLayoutManager(linearLayoutManager);
        activitySearchBinding.searchRecyclerView.setAdapter(smecSearchAdapter);

        viewGroup = (ViewGroup) getWindow().getDecorView();
        bottomDialog = new BottomDialog(this, R.style.BottomDialog , mRxBus);
        _searchClick();
        _dailogClick();
        //_submit();
        _getMsg();
        _setEditext();
    }

    public void _setEditext(){
        activitySearchBinding.edSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                activitySearchBinding.ivDelete.setVisibility(View.VISIBLE);
                activitySearchBinding.ivSearch.setImageResource(R.drawable.smec_remes_lightsearch);
            }
        });

        activitySearchBinding.ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activitySearchBinding.edSearch.setText("");
                condition="";
            }
        });
    }

    public void _getMsg(){
        activitySearchBinding.searchTopbar.setTopBarListener(new TopBarLayout.TopBarListener() {
            @Override
            public void setOnLeftClickListener() {
                ArrayList<AbleMatnr> arrayList=new ArrayList<>();
                arrayList.addAll(smecSearchAdapter.getBuycarList());
                mRxBus.post("SearchActivity",arrayList);
                finish();
            }

            @Override
            public void setOnRight1ClickListener() {

            }

            @Override
            public void setOnRight2ClickListener() {
                scanning=true;
                startActivityForResult(new Intent(SmecSearchActivity.this, CaptureActivity.class), CaptureActivity.REQ_CODE);
            }
        });
        activitySearchBinding.ptr.setHeaderView(WmsConstant.getSinaRefreshView());
        activitySearchBinding.ptr.setBottomView(new LoadingView(getApplicationContext()));
        activitySearchBinding.ptr.setAutoLoadMore(true);
        activitySearchBinding.ptr.setEnableOverScroll(false);
        activitySearchBinding.ptr.setEnableLoadmore(false);
        activitySearchBinding.ptr.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                if(scanning){
                    first=false;
                }
                if(first){
                    mPresenter.tenMantr();
                    first=false;
                }else {
                    activitySearchBinding.ptr.setEnableLoadmore(true);
                    pageNumber=1;
                    status="onRefresh";
                    mPresenter.ableMatnr(condition,pageNumber);
                    pageNumber+=1;
                }
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                if(!first){
                    status="onLoadMore";
                    mPresenter.ableMatnr(condition,pageNumber);
                    pageNumber+=1;
                }
            }
        });
        activitySearchBinding.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
                activitySearchBinding.ptr.startRefresh();
            }
        },300);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CaptureActivity.REQ_CODE:
                switch (resultCode) {
                    case RESULT_OK:
                        Log.e("扫码",data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                        String a=data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT);
                        if(!TextUtils.isEmpty(data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT))){
                            condition=a;
                            activitySearchBinding.edSearch.setText(condition);
                        }
                        smecSearchAdapter._clearList();

                        activitySearchBinding.ptr.setEnableLoadmore(true);
                        activitySearchBinding.ptr.startRefresh();
                        break;
                    case RESULT_CANCELED:
                        if (data != null) {
                            Log.e("SSS","ssss");
                        }
                        break;
                }
                break;
        }
    }


    /**
     * 搜索栏目
     */
    public void _searchClick(){
        activitySearchBinding.ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(activitySearchBinding.edSearch.getText().toString())){
                    condition=activitySearchBinding.edSearch.getText().toString();
                }else {
                    condition="";
                }
                CommonUtils.hideImmManager(activitySearchBinding.getRoot());
                activitySearchBinding.llPrompt.setVisibility(View.GONE);
                activitySearchBinding.ptr.startRefresh();
                activitySearchBinding.ptr.setEnableLoadmore(true);
            }
        });
        activitySearchBinding.edSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    if(!TextUtils.isEmpty(activitySearchBinding.edSearch.getText().toString())){
                        condition=activitySearchBinding.edSearch.getText().toString();
                    }else {
                        condition="";
                    }
                    activitySearchBinding.llPrompt.setVisibility(View.GONE);
                    CommonUtils.hideImmManager(v);
                    activitySearchBinding.ptr.setEnableLoadmore(true);
                    activitySearchBinding.ptr.startRefresh();
                }
                return false;
            }
        });
    }



    /**
     * 显示popuWindow
     */
    public void _dailogClick(){
        activitySearchBinding.cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _showPopuWindow(v);
            }
        });
    }

    @Override
    public SmecRequestPresenter getPresenter() {
        return new SmecRequestPresenter(this);
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(ten)
            }
    )
    public void _tenSuccess(final ArrayList<AbleMatnr> arrayList){
        if(CommonUtils.notEmpty(arrayList)){
            for(int i=0;i<arrayList.size();i++){
                _getPrice(arrayList.get(i).getMatnr(),i);
            }
            newArraylist=arrayList;
            if(CommonUtils.notEmpty(newArraylist)){
                smecSearchAdapter.setArrayList(newArraylist,"onRefresh");
            }
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                activitySearchBinding.ptr.finishRefreshing();
            }
        },200);
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(tenFail)
            }
    )
    public void _tenFail(String a){
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                activitySearchBinding.ptr.finishRefreshing();
            }
        },200);
    }


    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(SEARCH)
            }
    )
    public void _searchSuccess(final ArrayList<AbleMatnr> arrayList){
        if(CommonUtils.notEmpty(arrayList)){
            for(int i=0;i<arrayList.size();i++){
                _getPrice(arrayList.get(i).getMatnr(),i);
            }
            newArraylist=arrayList;
            if(CommonUtils.notEmpty(newArraylist)){
                smecSearchAdapter.setArrayList(newArraylist,status);
            }
        }else {
            if(status.equals("onRefresh")){
                smecSearchAdapter._clearList();
            }
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(status.equals("onRefresh")){
                    activitySearchBinding.ptr.finishRefreshing();
                }else {
                    activitySearchBinding.ptr.finishLoadmore();
                }
            }
        },200);
    }

    /**
     *  获取价格
     */
    public void _getPrice(final String mantr, final int i){
        Map<String, String> params = new HashMap<String, String>();
        params.put("arg0",mantr);
        String priceAdress= GetFullUrl.getFullUrl(_PriceUrl,params);
        OkHttpUtils.get().url(priceAdress).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                MantrPrice mantrPrice=gson.fromJson(response.toString(),MantrPrice.class);
                newArraylist.get(i).setMatnrPrice(mantrPrice.getPrice());
            }
        });
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(SEARCHFAIL)
            }
    )
    public void _searchFail(String a){
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                activitySearchBinding.ptr.finishRefreshing();
            }
        },500);
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(BUY_NULL)
            }
    )
    public void buyNull(Object o){
        smecSearchAdapter.setBuycarList(new ArrayList<AbleMatnr>());
        activitySearchBinding.cartNum.setVisibility(View.GONE);
    }

    /**
     *
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(BUY_NOT_NULL)
            }
    )
    public void buyNotNull(final HashMap<String, Object> hashMap){
        if(hashMap.size() == 3) {
            //获取起始坐标
            int[] startPoint = new int[2];
            startPoint[0] = (int) hashMap.get("x");
            startPoint[1] = (int) hashMap.get("y");

            //获取结束坐标
            int[] endPoint = new int[2];
            activitySearchBinding.cartBox.getLocationInWindow(endPoint);


            //生成View
            CircleView view = new CircleView(SmecSearchActivity.this);
            view.setCircleStartPoint(startPoint[0], startPoint[1]);
            view.setCircleEndPoint(endPoint[0] + activitySearchBinding.cartBox.getWidth() / 2 + 10, endPoint[1]);
            //添加View并执行动画
            viewGroup.addView(view);
            view.startAnimation();

            activitySearchBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    activitySearchBinding.cartNum.setVisibility(View.VISIBLE);
                    activitySearchBinding.cartNum.setText((String) hashMap.get("size"));
//                    smecSearchAdapter.setBuycarList((ArrayList<AbleMatnr>)hashMap.get("newList"));
                }
            }, 600);
        }else{
            activitySearchBinding.cartNum.setVisibility(View.VISIBLE);
            activitySearchBinding.cartNum.setText((String) hashMap.get("size"));
            smecSearchAdapter.setBuycarList((ArrayList<AbleMatnr>)hashMap.get("newList"));
        }

    }

    /**
     *
     * @param arrayList
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(RequestMantr)
            }
    )

    public void _SelectMantr(ArrayList<AbleMatnr> arrayList){
        if(CommonUtils.notEmpty(arrayList)){
            String num= String.valueOf(arrayList.size());
            smecSearchAdapter._setBuyList(arrayList);
            activitySearchBinding.cartNum.setVisibility(View.VISIBLE);
            activitySearchBinding.cartNum.setText(num);
        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(Top)
            }
    )
    public void _top(final String a){
        activitySearchBinding.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
                linearLayoutManager.scrollToPositionWithOffset(Integer.parseInt(a),0);
                linearLayoutManager.setStackFromEnd(true);
            }
        },600);
    }

    /**
     * 显示悬浮框
     */
    private void _showPopuWindow(View view){
        _loadData();
        if(CommonUtils.notEmpty(bottomDialog.getArrayList())){
            bottomDialog.show();
        }else {
            Toast.makeText(SmecSearchActivity.this,"无添加物料",Toast.LENGTH_SHORT).show();
        }
    }

    private void _loadData(){
        bottomDialog.setArrayList(smecSearchAdapter.getBuycarList());
    }


    @Override
    protected void onResume() {
        super.onResume();
        activitySearchBinding.llPrompt.setVisibility(View.VISIBLE);
        first=true;
        activitySearchBinding.ptr.setEnableLoadmore(false);
    }
}
